﻿#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QFileDialog>
#include <QMessageBox>

MainWindow::MainWindow(QWidget* parent)
	: QMainWindow(parent)
	, ui(new Ui::MainWindow())
{
	ui->setupUi(this);
	// 创建图片显示控件
	imageWidget = new ImageWidget(this);
	ui->scrollArea->setWidget(imageWidget);

	// 设置状态栏
	statusLabel = new QLabel(this);
	statusBar()->addWidget(statusLabel);

	// 连接信号槽
	connect(ui->loadButton, &QPushButton::clicked, this, &MainWindow::onLoadButtonClicked);
	connect(imageWidget, &ImageWidget::pixelPositionChanged, this, &MainWindow::updateStatusBar);
	QStringList ips = Camera::GetCameraList();
	ui->comboBox->addItems(ips);
}

MainWindow::~MainWindow()
{
	delete ui;
}
//void MainWindow::onLoadButtonClicked()
//{
//	QString path = ui->lineEdit->text().trimmed();
//	if (!path.isEmpty()) {
//		if (imageWidget->loadImage(path)) {
//			statusBar()->showMessage("图片加载成功", 2000);
//		} else {
//			statusBar()->showMessage("无法加载图片: " + path, 3000);
//		}
//	}
//}

void MainWindow::updateStatusBar(const QString& info)
{
	statusLabel->setText(info);
}

// 选择路径
void MainWindow::on_toolButton_clicked()
{
	QString path = QFileDialog::getExistingDirectory(this,
		"选择文件保存路径", QCoreApplication::applicationDirPath());
	path += "/";
	ui->pathEdit->setText(path);
	if (!path.isEmpty()) {
		m_savePath = path;
		m_cal.SetSavePath(path);
	}
}
// 清空文件夹
void MainWindow::on_pushButton_clicked()
{
	auto but = QMessageBox::question(this, "警告",
		"该操作会将当前文件夹内所有文件删除，请谨慎操作,选择Yes继续当前操作");
	if (but != QMessageBox::Yes) {
		return;
	}

	// 清空文件夹
	QDir dir(m_savePath);
	if (!dir.exists()) return;

	dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
	QFileInfoList fileList = dir.entryInfoList();

	foreach(const QFileInfo & fileInfo, fileList) {
		if (fileInfo.isDir()) {
			QDir(fileInfo.absoluteFilePath()).removeRecursively();
		} else {
			QFile::remove(fileInfo.absoluteFilePath());
		}
	}
}
// 加载内参
void MainWindow::onLoadButtonClicked()
{
	if (m_savePath.isEmpty()) {
		QMessageBox::information(this, "提示", "请先设置文件保存路径");
		return;
	}
	if (m_camera == nullptr) {
		QMessageBox::information(this, "提示", "请先选择要标定的相机");
		return;
	}

	if (!m_camera->SaveCameraParamater(m_paramPath) || m_paramPath.isEmpty()) {
		QMessageBox::warning(this, "提示", "内参数据获取失败, 请重试");
		return;
	}
	QFile file(m_paramPath);
	if (!file.exists()) {
		QMessageBox::warning(this, "提示", "未找到内参文件, 请重试");
		return;
	}

	if (!file.open(QIODevice::ReadOnly)) {
		QMessageBox::warning(this, "提示", "内参文件打开失败, 请重试");
		return;
	}

	QByteArray data = file.readAll();
	ui->textBrowser->clear();
	ui->textBrowser->append(data);
	file.close();
}
// 选择相机
void MainWindow::on_loadButton_2_clicked()
{
	if (m_savePath.isEmpty()) {
		QMessageBox::information(this, "提示", "请先设置文件保存路径");
		return;
	}

	if (m_camera != nullptr) {
		auto but = QMessageBox::question(this, "警告",
			"该操作会切换拍照相机，点击YES继续选择Yes继续当前操作");
		if (but != QMessageBox::Yes) {
			return;
		}
		delete m_camera;
	}

	QString ipstring = ui->comboBox->currentText().trimmed();

	QStringList ips = ipstring.split('-');
	if (ips.size() != 2) {
		QMessageBox::warning(this, "警告", "相机IP数据异常");
		return;
	}
	if (ips.at(1) == "MMIND") {
		m_camera = Camera::GetCameraObject(CameraBrand::camera_brand_mmind);
	} else if (ips.at(1) == "TEST") {
		m_camera = Camera::GetCameraObject(CameraBrand::camera_brand_test);
	}
	if (m_camera == nullptr) {
		QMessageBox::warning(this, "警告", "获取相机实例失败, 请重试");
		return;
	}

	CameraParam param = {};
	param.ip = ips.at(0);
	param.id = "标定";
	param.path = m_savePath;
	if (m_camera->CameraInit(param) != 0) {
		QMessageBox::warning(this, "警告", "相机初始化失败, 请重试");
		delete m_camera;
		m_camera = nullptr;
	} else {
		QMessageBox::information(this, "提示", "相机选择成功");
	}
}
void MainWindow::ShowData()
{
	if (m_current.index <= 0) {
		ui->label_20->setText("0");
		return;
	}
	ui->label_20->setText(QString::number(m_current.index));
	ui->lineEdit->setText(m_current.rgb);
	ui->lineEdit_2->setText(m_current.depth);
	imageWidget->loadImage(m_current.rgb);
	ui->spinBox->setValue(m_current.pix_x);
	ui->spinBox_2->setValue(m_current.pix_y);

	ui->doubleSpinBox->setValue(m_current.rob.x);
	ui->doubleSpinBox_2->setValue(m_current.rob.y);
	ui->doubleSpinBox_3->setValue(m_current.rob.z);
	ui->doubleSpinBox_4->setValue(m_current.rob.a);
	ui->doubleSpinBox_9->setValue(m_current.rob.b);
	ui->doubleSpinBox_10->setValue(m_current.rob.c);
}

bool MainWindow::SaveOldData()
{
	if (m_current.index != 0) {
		m_current.rgb = ui->lineEdit->text().trimmed();
		m_current.depth = ui->lineEdit_2->text().trimmed();
		m_current.pix_x = ui->spinBox->value();
		m_current.pix_y = ui->spinBox_2->value();
		if (m_current.pix_x == 0 && m_current.pix_y == 0) {
			auto but = QMessageBox::question(this, "警告",
				"检测到当前数据的像素数据未设置，是否直接切换到其它图片，点击Yes继续");
			if (but != QMessageBox::Yes) {
				return false;
			}
		}
		if (!m_current.valid) {
			m_current.rob.x = ui->doubleSpinBox->value();
			m_current.rob.y = ui->doubleSpinBox_2->value();
			m_current.rob.z = ui->doubleSpinBox_3->value();
			m_current.rob.a = ui->doubleSpinBox_4->value();
			m_current.rob.b = ui->doubleSpinBox_9->value();
			m_current.rob.c = ui->doubleSpinBox_10->value();
		}
		if (m_current.rob.b != 0 || (m_current.rob.c != 180 && m_current.rob.c != -180)) {
			auto but = QMessageBox::question(this, "警告",
				"检测到当前数据的机械手坐标数无效，是否直接切换到其它图片，点击Yes继续");
			if (but != QMessageBox::Yes) {
				return false;
			}
		} else {
			m_current.valid = true;
		}
		if (m_info.contains(m_current.index)) {
			m_info[m_current.index] = m_current;
		} else {
			m_info.insert(m_current.index, m_current);
		}
		return true;
	}

	return true;
}

// 拍照
void MainWindow::on_pushButton_2_clicked()
{
	if (m_camera == nullptr) {
		QMessageBox::warning(this, "警告", "请先选择需要标定的相机, 再拍照");
		return;
	}
	if (!SaveOldData()) {
		return;
	}

	BDInfo temp = {};
	temp.index = ui->comboBox_2->count() + 1;
	temp.valid = false;
	if (!m_camera->SnapPicture(temp.rgb, temp.depth)) {
		QMessageBox::warning(this, "警告", "相机未能正常拍照, 请重试");
		return;
	}
	ui->lineEdit->setText(temp.rgb);
	ui->lineEdit_2->setText(temp.depth);
	m_current = temp;
	ui->comboBox_2->addItem(QString("第%1张").arg(temp.index));
	ShowData();
}
// 手动选择
void MainWindow::on_pushButton_3_clicked()
{
	if (!SaveOldData()) {
		return;
	}
	int idx = ui->comboBox_2->currentIndex() + 1;
	if (idx == m_current.index) {
		return;
	}
	if (!m_info.contains(idx)) {
		QMessageBox::warning(this, "警告", "未匹配到对应数据");
		return;
	}
	m_current = m_info.value(idx);
	ShowData();
}

// 手动选择,删除数据
void MainWindow::on_pushButton_6_clicked()
{
	int idx = ui->comboBox_2->currentIndex() + 1;
	if (!m_info.contains(idx)) {
		m_info.remove(idx);
	}
	if (idx == m_current.index) {
		m_current = {};
		for (auto& iter : m_info) {
			if (iter.index > 0) {
				m_current = iter;
				break;
			}
		}
	}
}

// 读取坐标
void MainWindow::on_pushButton_4_clicked()
{
	QMessageBox::warning(this, "警告", "功能暂时不支持");
}

// 生成标定文件
void MainWindow::on_pushButton_5_clicked()
{
	//QMessageBox::warning(this, "警告", "功能暂时不支持");
	if (m_paramPath.isEmpty()) {
		QMessageBox::information(this, "提示", "请先获取相机内参");
		return;
	}
	m_cal.InitCameraParam(m_paramPath);
	if (m_info.size() < 3) {
		QMessageBox::information(this, "提示", "照片数据应该至少3组以上");
		return;
	}
	QVector<BDInfo> info(m_info.size());
	for (auto& iter : m_info) {
		if (iter.pix_x == 0 && iter.pix_y == 0) {
			auto but = QMessageBox::question(this, "警告",
				QString("第%1张图片像素点位错误，点击Yes跳过当前数据, No结束标定")
				.arg(iter.index));
			if (but != QMessageBox::Yes) {
				return;
			} else {
				continue;
			}
		}
		info.append(iter);
	}
	m_cal.Calculate(info);
}
